<template>
    <el-tabs v-model="tabs" class="demo-tabs" @tab-click="handleClick"
        style="width: 98%;;background: #fff;padding: 20px;box-sizing: border-box;">
        <el-tab-pane label="表单设计" name="first">
            <div class="bth-report" v-if="!isCheck">
                <el-button @click="goback" type="primary">返回</el-button>
                <el-button @click="savebg" type="primary">保存</el-button>
                <el-button @click="submitForm(ruleFormRef)" v-if="users.userRole != '1'" type="primary">上报</el-button>
            </div>
            <div class="table-box">
                <div class="table-title">
                    {{ infoMsg.title }}
                </div>
                <div class="agencyName">区中园名称：<el-input style="width: 160px;" v-model="infoMsg.agencyName"
                        :disabled="isCheck" placeholder="请输入机关名称" /></div>
            </div>
            <el-form label-position="right" :model="infoMsg" style="width: 100%;" ref="ruleFormRef" :rules="rules">
                <div class="inforMsg">
                    <div class="infor-item">
                        <el-form-item prop="unit" label="单位：">
                            <el-input style="width: 350px;" v-model="infoMsg.unit" :disabled="isCheck"
                                placeholder="请输入单位" />
                        </el-form-item>
                    </div>
                    <div class="infor-item">
                        <el-form-item prop="duties" label="职务：">
                            <el-input style="width: 350px;" v-model="infoMsg.duties" :disabled="isCheck"
                                placeholder="请输入职务" />
                        </el-form-item>
                    </div>
                    <div class="infor-item">
                        <el-form-item prop="preparer" label="填表人：">
                            <el-input style="width: 350px;" v-model="infoMsg.preparer" :disabled="isCheck"
                                placeholder="请输入填表人" />
                        </el-form-item>
                    </div>
                    <div class="infor-item">
                        <el-form-item prop="phone" label="手机：">
                            <el-input style="width: 350px;" v-model="infoMsg.phone" :disabled="isCheck"
                                placeholder="请输入手机号码" />
                        </el-form-item>
                    </div>
                </div>
            </el-form>
            <el-table max-height="900"  
            border 
            :data="form.tableData" 
            v-loading="loading"
                style="width: 100%;" :header-cell-style="{
                    background: '#E7F2FF',
                    color: 'black',
                    height: '60px',
                    textAlign: 'center',
                }">
                <el-table-column label="序号" type="index" width="60"/>
                <el-table-column label="项目名称">
                    <template #default="{ row, $index }">
                        
                        <el-input autosize :rows="3"
    type="textarea" style="width: 100%;" v-model="row.name" :disabled="isCheck"
                            placeholder="" />
                    </template>
                </el-table-column>
                <el-table-column label="投资企业名称">
                    <template #default="{ row, $index }">
                        <el-input autosize :rows="3"
    type="textarea" style="width: 100%;" v-model="row.cName" :disabled="isCheck"
                            placeholder="" />
                    </template>
                </el-table-column>
                <el-table-column label="投资来源">
                    <template #default="{ row, $index }">
                        <el-input autosize :rows="3"
    type="textarea" style="width: 100%;" v-model="row.source" :disabled="isCheck"
                            placeholder="" />
                    </template>
                </el-table-column>
                <el-table-column label="开工时间" width="180">
                    <template #default="{ row, $index }">
                        <el-date-picker :disabled="isCheck" v-model="row.date" placeholder="" style="width: 100%;"
                            format="YYYY年MM月DD日" type="dates" value-format="YYYY年MM月DD日" />
                    </template>
                </el-table-column>
                <el-table-column label="项目状态">
                    <template #default="{ row, $index }">
                        <el-input autosize :rows="3"
    type="textarea" style="width: 100%;" v-model="row.state" :disabled="isCheck"
                            placeholder="" />
                    </template>
                </el-table-column>
                <el-table-column label="项目分类">
                    <template #default="{ row, $index }">
                        <el-input autosize :rows="2"
    type="textarea" style="width: 100%;" v-model="row.class" :disabled="isCheck"
                            placeholder="" />
                    </template>
                </el-table-column>
                <el-table-column label="总投资（万元）"  width="120">
                    <template #default="{ row, $index }">
                        <el-input autosize type="number" style="width: 100%;" v-model="row.all" :disabled="isCheck"
                            placeholder="" />
                    </template>
                </el-table-column>
                <el-table-column label="累计到位资金（万元）" width="120">
                    <template #default="{ row, $index }">
                        <el-input autosize type="number" style="width: 100%;" v-model="row.get" :disabled="isCheck"
                            placeholder="" />
                    </template>
                </el-table-column>
                <el-table-column label="2022年到位资金（万元）" width="120">
                    <template #default="{ row, $index }">
                        <el-input autosize type="number" style="width: 100%;" v-model="row.getTwo" :disabled="isCheck"
                            placeholder="" />
                    </template>
                </el-table-column>
                <el-table-column label="吸纳就业">
                    <el-table-column label="人数" width="120">
                        <template #default="{ row, $index }" >
                            <el-input type="number" style="width: 100%;" v-model="row.pNumO" :disabled="isCheck"
                                placeholder="" />
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column label="吸纳农村劳动力就业">
                    <el-table-column label="人数"  width="120">
                        <template #default="{ row, $index }">
                            <el-input type="number" style="width: 100%;" v-model="row.pNumT" :disabled="isCheck"
                                placeholder="" />
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column label="吸纳贫困就业">
                    <el-table-column label="人数"  width="120">
                        <template #default="{ row, $index }">
                            <el-input type="number" style="width: 100%;" v-model="row.pNumTh" :disabled="isCheck"
                                placeholder="" />
                        </template>
                    </el-table-column>
                </el-table-column>
                <el-table-column label="2022年利益联结带贫">
                    <el-table-column label="户数"  width="120">
                        <template #default="{ row, $index }">
                            <el-input type="number" style="width: 100%;" v-model="row.hNum" :disabled="isCheck"
                                placeholder="" />
                        </template>
                    </el-table-column>
                    <el-table-column label="人数"  width="120">
                        <template #default="{ row, $index }">
                            <el-input type="number" style="width: 100%;" v-model="row.pNum" :disabled="isCheck"
                                placeholder="" />
                        </template>
                    </el-table-column>
                </el-table-column>
            </el-table>
            <div class="totals">
                <div class="left-box">合计</div>
                <div class="right-box">
                    <div class="right-item">
                        {{ getTotals('all') }}
                    </div>
                    <div class="right-item">
                        {{ getTotals('get') }}   
                    </div>
                    <div class="right-item">
                        {{ getTotals('getTwo') }}  
                    </div>
                    <div class="right-item">
                        {{ getTotals('pNumO') }}  
                    </div>
                    <div class="right-item">
                        {{ getTotals('pNumT') }}   
                    </div>
                    <div class="right-item">
                        {{ getTotals('pNumTh') }}
                    </div>
                    <div class="right-item">
                        {{ getTotals('hNum') }}                       
                    </div>
                    <div class="right-item">
                        {{ getTotals('pNum') }}
                      
                    </div>
                </div>
            </div>
            <div class="addbox" v-if="!isCheck">
                <div class="icon" @click="addRows()">
                    <el-icon :size="25" color="#666666">
                        <Plus />
                    </el-icon>
                </div>
            </div>
        </el-tab-pane>
        <el-tab-pane :label="users.userRole == '1' ? '文件查看' : '文件上传'" name="second">
            <upfiles :id="id" />
        </el-tab-pane>
    </el-tabs>
</template>
 
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import upfiles from '@/components/upfiles.vue';
import { useRoute, useRouter } from "vue-router";
import type { FormInstance, TabsPaneContext } from 'element-plus'
import { ElMessage } from 'element-plus'
import { reportfindById, reportpublish, editReports } from "@/util/api";
import { useStore } from '@/store'
const ruleFormRef = ref<FormInstance>();
const store = useStore()
const router = useRouter()
const users = store.state.userInfo
const query = useRoute().query
const id: any = ref("")
const isCheck: any = ref(false)
const templateId: any = ref('')//报表类型
const tabs: any = ref('')//展示的tab
const dataCopy: any = ref({})//报表原始数据
const infoMsg: any = ref({})
const loading = ref(false)
const nowtableNo = ref('')
const form = ref({
    tableData: <any>[]
})
const rules = reactive({
    duties: [
        { required: true, message: '请输入职务', trigger: 'blur' },
    ],
    preparer: [
        { required: true, message: '请输入填表人', trigger: 'blur' },
    ],
    unit: [
        { required: true, message: '请输入单位', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
    ],
})
//获取报表 
const getTable = async () => {
    loading.value = true
    let res: any = await reportfindById(query.id)
    console.log(res)
    dataCopy.value = res.data
    let list = []
    if (res.data.list != null && res.data.list != 'null') {
        list = JSON.parse(res.data.list)
        form.value.tableData = list
        console.log(list)
    } else {
        form.value.tableData = [
            {
                name: "",
                cName: "",
                source: "",
                date: "",
                state: "",
                class: "",
                all: "",
                get: "",
                getTwo: "",
                pNumO: "",
                pNumT: "",
                pNumTh: "",
                hNum: "",
                pNum: ""
            }
        ]
    }
    if (res.data.info != null && res.data.info != 'null') {
        infoMsg.value = JSON.parse(res.data.info)
        infoMsg.value['tableNo'] = nowtableNo.value
    }
    infoMsg.value.title = res.data.name
    loading.value = false
}

const  getTotals=(key:any)=>{
    let sum = 0
    form.value.tableData.forEach(v => {
         sum+=Number(v[key])
    });
     return sum
}
const inputChange=(e:any,index:Number)=>{
    console.log(e)

}
//返回
const goback = () => {
    router.push('/monthReport')
}
//保存报表
const  savebg= async() => {
    saveInfo()
     let res:any = await editReports(dataCopy.value)
     if(res.code=='200')ElMessage.success('已保存') 
}
const saveInfo=()=>{
    if(!infoMsg.value.time){
        infoMsg.value.time = getCurrentTime()
    }
    if(!infoMsg.value.agencyName||infoMsg.value.agencyName==null){
        infoMsg.value.agencyName = dataCopy.value.developArea
    }
    dataCopy.value.info = JSON.stringify(infoMsg.value)
    dataCopy.value.list = JSON.stringify(form.value.tableData)
}
//上报
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
    if (!valid) return ElMessage.error('请填写完整再上报')    
    if(dataCopy.value.filesQ==null)return ElMessage.error('请先左上角上传文件')
    saveInfo()
    editReports(dataCopy.value).then(async (saves:any)=>{
        if(saves.code!='200')return
        let res:any= await reportpublish(id.value)
        if(res.code=='200'){
            router.push('/Park1')
        }  
    })
    
    })
  }



const repair = (i: any) => {
    if (i >= 0 && i <= 9) {
        return "0" + i;
    } else {
        return i;
    }
}
const getCurrentTime = () => {
    var date = new Date();//当前时间
    var year = date.getFullYear() //返回指定日期的年份
    var month = repair(date.getMonth() + 1);//月
    var day = repair(date.getDate());//日
    //当前时间 
    var curTime = year + "-" + month + "-" + day;
    return curTime;
}
//添加行
const addRows = () => {
    const circle = form.value.tableData[0]; //取出数组中第一个对象
    if (circle) {
        const newObj = {};
        for (let key in circle) { //把第一个对象的属性都赋值给新对象newObj  然后每个属性的值都设置为空；
            newObj[key] = '';
        }
        form.value.tableData.splice(form.value.tableData.length, 0, newObj);
    }
}
const handleClick = (tab: TabsPaneContext, event: Event) => {
    getTable()
}
onMounted(() => {
    // console.log(query.isCheck)
    templateId.value = query.radio1
    tabs.value = query.tabs
    id.value = query.id
    if(query.isCheck){
        isCheck.value=true
    }else{
        isCheck.value=false
    }
    nowtableNo.value = "经开区统3表"
    getTable()
})
</script>
<style scoped>
.demo-tabs {
    width: 100vw;
    padding-bottom: 60px;
}

.table-box {
    width: 100%;
    box-sizing: border-box;
    border: 1px solid rgb(102, 102, 102);
    margin-top: 20px;
}

.agencyName {
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom: 1px solid rgb(102, 102, 102);
    height: 60px;
}

.msg-box {
    display: flex;
    justify-content: right;
    border-bottom: 1px solid black;
    border-top: 1px solid rgb(102, 102, 102);
    padding: 30px 0;
}

.table-title {
    text-align: center;
    font-size: 24px;
    background-color: #FF0000;
    line-height: 50px;
    color: #ffffff;
    border-bottom: 1px solid rgb(102, 102, 102);
}

.bth-report {
    width: 100%;
    display: flex;
    justify-content: right;
}

.inforMsg {
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.infor-item {
    width: 25%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    border: 1px solid rgb(102, 102, 102);
    border-top: none;
    padding-top: 20px;
}

.demo {
    border: 1px solid rgb(102, 102, 102);
    border-top: none;
    box-sizing: border-box;
    padding: 10px;
}

.demo div {
    margin: 10px 0;
}

.addbox {
    width: 100%;
}

.icon {
    width: 40px;
    height: 30px;
    text-align: center;
    line-height: 40px;
    border: 1px solid #666666;
    border-top: none;
    box-sizing: border-box;
    margin: 0 auto;
    cursor: pointer;
}
.totals{
    width: 100%;
    display: flex;
    border: 1px solid #DCDFE6;
    border-top: none;
    box-sizing: border-box;
    height: 40px;
    background-color: #E7F2FF;
    color: #606266;
}
.left-box{
    flex: 1;
    text-align: center;
    line-height: 40px;
}
.right-box{
    display: flex;
    justify-content: right;
    .right-item{
        width: 120px;
        line-height: 40px;
        padding-left: 20px;
        box-sizing: border-box;
        border-left: 1px solid #DCDFE6;
    }
}
</style>